import { modal } from 'vue-strap'
import datepicker from 'vue-datepicker'
import getDatePickerOption from '../../../../util/date-picker-option'
import { showMsg, updateCGB } from '../../../../vuex/action'

export default {
  name: 'cgb-update',
  components: {
    modal: modal,
    'vue-datepicker': datepicker
  },
  props: ['cgb'],
  data() {
    return {
      datePickerOption: getDatePickerOption(),
      showModal: false
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xUpdateCGB: updateCGB
    }
  },
  methods: {
    validCheck() {
      var cgb = this.cgb
      var key
      var inputs = [
        'name',
        'code',
        'leastMoney',
        'increase',
        'investmentAmount',
        'location',
        'shareTitle',
        'shareContent',
        'thoughts',
        'articleTopicId'
      ]
      for (key of inputs) {
        if (cgb[key] === null || cgb[key].length === 0) {
          return '* 标记的都为必填项'
        }
      }
      key = null
    },
    submit() {
      var checkMsg = this.validCheck()
      if (checkMsg) {
        return this.xShowMsg({
          type: 'danger',
          content: checkMsg
        })
      }
      var formData = new FormData()
      var cgb = this.cgb
      for (let key of [
        'id',
        'name',
        'code',
        'category',
        'leastMoney',
        'increase',
        'investmentAmount',
        'location',
        'shareTitle',
        'shareContent',
        'thoughts',
        'articleTopicId',
        'homeShow',
        'status',
        'description',
        'publishTime'
      ]) {
        formData.append(key, cgb[key] + '')
      }
      ;[
        'blockPicFile',
        'picFile',
        'logoPicFile',
        'sharePicFile'
      ].forEach(key => {
        var files = this.$els[key.toLowerCase()]['files']
        if (files.length) {
          formData.append(key, files[0])
        }
      })

      this.xUpdateCGB(formData)
        .then(() => {
          this.$els.form.reset()
          this.showModal = false
        })
        .catch(res => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
